<?php
/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/7/21
 * Time: 10:39
 */
require_once APPPATH.'third_party/wxpayapi/lib/phpqrcode.php';

class Image_model extends Base_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('image_lib');
    }
    public function createSlsPost($postId,$sls)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $post=$redis->get('slspost.'.$postId.'.'.$sls);
        if ($post===false){
            //获取海报
            $this->load->database();
            $oripost=$this->db->select('url,hor,vrt,qrwidth,qrheight,link')->from('mod_salesman_post')->where(array('id'=>$postId))->get()->row_array();
            //生成短链接
            $url=urlencode($oripost['link'].'sls='.$sls);
            $url=$this->longurl2short('https://h5.youzan.com/v2/trade/directsellerJump/jump?kdt_id=18168297&sl='.$sls.'&redirect_uri='.$url);
            //生成二维码
            if ($url['errcode']===0){
                $qrcode = $this->qrcode($url['short_url'],$postId,$sls);
            }else{ return false;}
            //处理二维码
            $config=array();
            $config['source_image']=$qrcode['file'];//源文件地址
            $qrpath=$qrcode['dir'].$sls.'.png';//处理后地址
            $config['new_image']=$qrpath;
            $config['height']=$oripost['qrheight'];
            $config['width']=$oripost['qrwidth'];
            $this->resize($config);
            //添加二维码到海报
            $config=array();
            $config['wm_vrt_alignment']='top';
            $config['wm_hor_alignment']='left';
            $config['source_image']='/home/nldou/webroot/wap'.$oripost['url'];//海报模板地址
            $newdir='/home/nldou/webroot/wap/upload/images/post/'.$postId.'/post/';
            if(!file_exists($newdir)){
                mkdir($newdir,0775,true);
            }
            $postpath=$newdir.$sls.'.jpg';//处理后海报地址
            $posturl='/upload/images/post/'.$postId.'/post/'.$sls.'.jpg';
            $config['new_image']=$postpath;
            $config['wm_type']='overlay';
            $config['wm_opacity']='100';
            $config['wm_overlay_path']=$qrpath;
            $config['wm_hor_offset']=(string)$oripost['hor'];
            $config['wm_vrt_offset']=(string)$oripost['vrt'];
            $this->overlay($config);
            //存入redis
            $redis->set('slspost.'.$postId.'.'.$sls,$posturl);
            return $posturl;
        }else{return $post;}
    }

    public function longurl2short($url)
    {
        $this->config->load('weixin');
        $appid = $this->config->item('nldou_fuwu_appid');
        $appsecret = $this->config->item('nldou_fuwu_appsecret');
        $wx_type = $this->config->item('nldou_fuwu_type');
        $this->load->library("wxinterface/Wxinterface",array("appid"=>$appid,"appsecret"=>$appsecret,"wxtype"=>$wx_type));
        $res=$this->wxinterface->longurl2short($url);
        return $res;
    }

    public function qrcode($url,$postId,$sls)
    {
        $filedir='/home/nldou/webroot/wap/upload/images/post/'.$postId.'/qrcode/';
        if(!file_exists($filedir)){
            mkdir($filedir,0775,true);
        }
        $filepath=$filedir.$sls.'_raw.png';
        QRcode::png($url,$filepath,'QR_ECLEVEL_L',8,3);
        return array('dir'=>$filedir,'file'=>$filepath);
    }

    public function createFmdkPost($userName,$userIcon,$uid)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $hasrank=$redis->zScore('fmdk:20170606:20170724:level',$uid);
        if ($hasrank===false) return false;

        $haspost=$redis->get('fmdk:20170606:20170724:poster:'.$uid);
        if ($haspost===false){
            //微信头像下载到本地
            $dir='/upload/images/usericons/';
            $iconpath=$this->downloadfromurl($userIcon,$dir,$uid);
            //压缩图片
            $config=array();
            $config['source_image']=$iconpath['filepath'];
            $config['height']=140;
            $config['width']=140;
            $this->resize($config);
            //水印
            $globalconfig=array();
            $sourcedir='/home/nldou/webroot/wap/upload/images/fmdk/careerpost/20170606_0724/'.$hasrank.'/';
            $createdir='/home/nldou/webroot/wap/upload/images/fmdk/careerpostcreated/20170606_0724/'.$hasrank.'/';
            if(!file_exists($createdir)){
                mkdir($createdir,0775,true);
            }
            $globalconfig['wm_vrt_alignment']='top';
            $globalconfig['wm_hor_alignment']='left';
            //用户名
            $config=$globalconfig;
            $config['source_image']=$sourcedir.$uid.'.jpg';
            $config['new_image']=$createdir.$uid.'.jpg';
            $config['wm_type']='text';
            $config['wm_font_path']='/home/nldou/webroot/web/fonts/yaheibold.ttf';
            $config['wm_font_color']='4c3b3b';
            $config['wm_text']=$userName;
            $config['wm_font_size']='20';
            $config['wm_hor_offset']='35';
            $config['wm_vrt_offset']='765';
            $this->overlay($config);
            //用户头像
            $config=$globalconfig;
            $config['source_image']=$createdir.$uid.'.jpg';
            $config['wm_type']='overlay';
            $config['wm_opacity']='100';
            $config['wm_overlay_path']=$iconpath['filepath'];
            $config['wm_hor_offset']='63';
            $config['wm_vrt_offset']='596';
            $this->overlay($config);

            $poster='http://wap.nldou.com/upload/images/fmdk/careerpostcreated/20170606_0724/'.$hasrank.'/'.$uid.'.jpg';
            $redis->set('fmdk:20170606:20170724:poster:'.$uid,$poster);
        }else{$poster=$haspost;}
        return $poster;

    }

    public function overlay($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->watermark()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function resize($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->resize()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function crop($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->crop()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function rotate($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->rotate()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function downloadfromurl($url,$dir,$filename)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);

        curl_close($ch);
        $media = array_merge(array('header'=>$httpinfo),array('body' => $package));

        //生成文件名
        preg_match('/\w\/(\w+)/i', $media["header"]["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        $filename.='.'.$fileExt;
//        $filename = md5(time().uniqid()).".{$fileExt}";

//        $dir="/upload/images/".date('Ymd',time()).'/';
        $fdir = '/home/nldou/webroot/wap'.$dir;
        if(!file_exists($fdir)){
            mkdir($fdir,0775,true);
        }
        file_put_contents($fdir.$filename,$media['body']);
        $url='http://wap.nldou.com'.$dir.$filename;
        return array('filepath'=>$fdir.$filename,'url'=>$url);
    }

    public function downloadwxusericon()
    {
        $dur=time();
        $limit=10;
        $offset=0;
        $this->load->database();
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        try{
            while(true){
                $this->db->reconnect();
                //获取图片地址
                $users=$this->db->select('uid,userIcon')->from('mod_user')->limit($limit,$offset)->get()->result_array();
                if (empty($users)) break;//用户遍历完毕
                foreach ($users as $u){
                    $config=array();
                    if (preg_match("/http:\/\//i",$u['userIcon'])>0){
                        //下载图片
                        $dir='/upload/images/usericons/';
                        $iconpath=$this->downloadfromurl($u['userIcon'],$dir,$u['uid']);
                    }else{
                        //本地图片
                        preg_match('/\w\.(\w+)/i', $u['userIcon'], $extmatches);
                        $config['new_image']='/home/nldou/webroot/wap/upload/images/usericons/'.$u['uid'].'.'.$extmatches[1];
                        $iconpath=array('filepath'=>'/home/nldou/webroot/wap'.$u['userIcon'],
                            'url'=>'http://wap.nldou.com/upload/images/usericons/'.$u['uid'].'.'.$extmatches[1]);
                    }
                    //压缩图片
                    $config['source_image']=$iconpath['filepath'];
                    $config['height']=140;
                    $config['width']=140;
                    $this->resize($config);
                    //保存到redis
                    $redis->set('usericon:'.$u['uid'],$iconpath['url']);
                    echo 'user '.$u['uid'].' '.$iconpath['url'].' saved'.PHP_EOL;
                }
                $offset+=$limit;
            }
            $dur=time()-$dur;
            echo 'complete! totalTime:'.date('i:s',$dur).PHP_EOL;
        }catch (Exception $e){
            $this->db->close();
            echo $e->getMessage().PHP_EOL;
            exit();
        }
    }
}